package com.cf.back.permission.controller;

import com.cf.crudweb.controller.CommonController;
import com.cf.user.permission.model.SystemPermission;
import com.cf.user.permission.service.SystemPermissionService;
import com.cf.user.permission.vo.Menu;
import com.cf.user.permission.vo.MenuVo;
import com.cf.vo.ResponseVo;
import com.cf.web.RequiredLogin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * game-server-PermissionController
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/31 上午 10:40
 */
@RequiredLogin
@RequestMapping("/systemPermission")
public class SystemPermissionController extends CommonController<SystemPermission, SystemPermissionService> {

    @Override
    protected String getPageDir() {
        return "systemPermission";
    }

    @ResponseBody
    @RequestMapping(value = "/rolePermission", method = {RequestMethod.GET})
    public ResponseVo<MenuVo> getSysMenu(long roleId) {
        List<Menu> menu = this.getService().getPermissionTree();
        List<SystemPermission> rolePermission = this.getService().getRolePermission(roleId);
        return ResponseVo.success(menuToVo(menu, rolePermission), "获取系统权限成功！");
    }

    @ResponseBody
    @RequestMapping(value = "/rolePermission", method = {RequestMethod.POST})
    public ResponseVo<MenuVo> updatePermission(long roleId, @RequestBody List<Long> permissionId) {
        boolean rtRst = this.getService().updateRolePermission(roleId, permissionId);
        return ResponseVo.success(rtRst, "修改角色权限成功！");
    }


    private MenuVo menuToVo(List<Menu> menu, List<SystemPermission> systemPermissions) {
        MenuVo menuVo = new MenuVo(menu);
        List<Long> ids = new ArrayList();
        systemPermissions.forEach(systemPermission -> {
            ids.add(systemPermission.getId());
        });
        menuVo.setExpanded(ids);
        menuVo.setChecked(ids);
        return menuVo;
    }
}
